<template>
  <div class="image-filter">
    <img v-if="processedImage" :src="processedImage" alt="处理后的图片" />
    <div class="filter-controls">
      <select v-model="currentFilter">
        <option value="natural">自然效果</option>
        <option value="defogging">去雾效果</option>
        <option value="sharpen">锐化效果</option>
        <option value="grayscale">黑白效果</option>
        <option value="invert">反色效果</option>
        <option value="vintage">老照片效果</option>
        <option value="mosaic">马赛克效果</option>
        <option value="gaussian">高斯模糊效果</option>
        <option value="colorSplit">颜色分离效果</option>
      </select>
      <input type="file" @change="handleImageUpload" accept="image/*" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount } from "vue";
import { PixiFilter } from "pixi-image-filter";
import type { FilterType, BatchFilterData } from "pixi-image-filter";

const processedImage = ref<string>("");
const currentFilter = ref<FilterType>("natural");
let filter: PixiFilter | null = null;

// 初始化滤镜实例
onMounted(() => {
  filter = new PixiFilter({
    width: 800,
    height: 800
  });
});

// 处理图片上传
const handleImageUpload = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0];
  if (file && filter) {
    const reader = new FileReader();
    reader.onload = async e => {
      const base64 = e.target?.result as string;
      await filter.loadImage(base64);
      const result = filter.applyFilter({
        filterType: currentFilter.value,
        label: "当前效果",
        result: ""
      });
      processedImage.value = result.result;
    };
    reader.readAsDataURL(file);
  }
};

// 监听滤镜类型变化
watch(currentFilter, () => {
  if (filter && processedImage.value) {
    const result = filter.applyFilter({
      filterType: currentFilter.value,
      label: "当前效果",
      result: ""
    });
    processedImage.value = result.result;
  }
});

// 组件销毁时清理资源
onBeforeUnmount(() => {
  if (filter) {
    filter.destroy();
    filter = null;
  }
});
</script>

<style scoped>
.image-filter {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.filter-controls {
  display: flex;
  gap: 10px;
}

img {
  max-width: 100%;
  height: auto;
}
</style>
